var fly = require("flyio") // 引入http请求库
var ENV = require("./env.json")
// 用户参数静态变量
var USERNAME = ENV.username // 用户登录手机号
var PASSWORD = ENV.password // 密码经md5处理
var NOTIFY_TYPE = ENV.notifyType // server酱通知接口
var SUCCESS_TEXT = "提速成功"
var LOGIN_FAIL = "登录失败"
var EXPIRE = "套餐已过期"
var ERROR_TEXT = "提速失败"
var WAIT_TIME = 60
var WAIT_TEXT = `等待${WAIT_TIME}秒后再执行`

// 全局变量
var debug = ENV.debug // 调试开关
var authorization = ''
var orderInfo = {}
debug && console.log('--------ENV--------')
debug && console.log(ENV)
//添加请求拦截器
fly.interceptors.request.use((request) => {
  request.timeout = 10 * 1000
  request.headers["Accept"] = "application/json, text/plain, */*";
  request.headers["Connection"] = "keep-alive";
  request.headers["sec-ch-ua"] = 'Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"';
  request.headers["Content-Type"] = "application/json;charset=UTF-8";
  request.headers["sec-ch-ua-mobile"] = "?0";
  request.headers["User-Agent"] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36";
  request.headers["Origin"] = "https://www.fangyb.com";
  request.headers["Sec-Fetch-Site"] = "same-site";
  request.headers["Sec-Fetch-Mode"] = "cors";
  request.headers["Sec-Fetch-Dest"] = "empty";
  request.headers["Referer"] = "https://www.fangyb.com/";
  request.headers["Accept-Language"] = 'zh-CN,zh;q=0.9,ja;q=0.8,en-US;q=0.7,en;q=0.6';
  return request;
})
//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (err) => {
    //发生网络错误后会走到这里
    debug && console.log('网络错误')
    debug && console.log(WAIT_TEXT)
    await sleep(WAIT_TIME * 1000)
  }
)
// 执行入口主函数
main()
// 主函数定义
async function main() {
  debug && console.log('进入主线程，开始跑码')
  let statusCode = await getStatusCode()
  if (statusCode === 'true') {
    console.log('开启中')
    console.log(WAIT_TEXT)
    await sleep(WAIT_TIME * 1000)
    return;
  } else {
    console.log('未开启')
  }
  const looginInfo = await login()
  const loginCode = looginInfo.code
  authorization = looginInfo.data
  if (loginCode === 0) {
    debug && console.log('登录成功')
  } else if (loginCode === 11) {
    debug && console.log('未注册，请检查手机号是否正确或前往注册后再次运行')
    return
  } else if (loginCode === 12) {
    debug && console.log('用户名或密码错误')
    return
  } else {
    debug && console.log(LOGIN_FAIL)
    notifyWechat('error', LOGIN_FAIL)
    return
  }
  orderInfo = await getOrderInfo()
  const now = new Date().valueOf()
  if (now >= orderInfo.validDate) {
    debug && console.log(EXPIRE)
    notifyWechat('error', EXPIRE)
    return
  } else {
    debug && console.log('未到期')
  }
  if (orderInfo.statusCode === 'true') {
    debug && console.log('开启中，不重复执行')
    return
  }
  // 提交订单
  const submitRes = await submit()
  statusCode = await getStatusCode()
  if (statusCode === 'true') {
    debug && console.log(SUCCESS_TEXT)
    notifyWechat('success', SUCCESS_TEXT)
    return;
  } else {
    debug && console.log(`${ERROR_TEXT}，${submitRes.msg}`)
    notifyWechat('error', `${ERROR_TEXT}，${submitRes.msg}`)
  }
  console.log(WAIT_TEXT)
  await sleep(WAIT_TIME * 1000)
}
// 执行登录操作
function login() {
  return new Promise((resolve, reject) => {
    fly.post('https://www.fangyb.com:2039/biz/user/login.do', { userName: USERNAME, userPassword: PASSWORD })
      .then(function (res) {
        debug && console.log('--------loginInfo--------');
        debug && console.log(res);
        resolve(res)
      })
      .catch(function (error) {
        console.log('loginError', error);
        reject(error)
      });
  })
}
// 获取提速状态(公共)
function getStatusCode() {
  return new Promise((resolve, reject) => {
    fly.post('https://www.fangyb.com:2039/biz/common/speedQuery.do', { userName: '' })
      .then(function (res) {
        debug && console.log('--------statusCode--------');
        debug && console.log(res.data.statusCode);
        resolve(res.data.statusCode)
      })
      .catch(function (error) {
        console.log('getStatusCodeError', error);
        reject(error)
      });
  })
}
// 获取提速订单详情
function getOrderInfo() {
  return new Promise((resolve, reject) => {
    fly.post('https://www.fangyb.com:2039/biz/common/myOrder.action', { userName: USERNAME }, { headers: { Authorization: authorization } })
      .then(function (res) {
        debug && console.log('--------orderInfo--------');
        const info = {
          statusCode: res.data.statusCode,
          className: res.data.orderDetail.list[0].className,
          orderId: res.data.orderDetail.list[0].orderId,
          validDate: new Date(res.data.orderDetail.list[0].validDate).valueOf()
        }
        debug && console.log(info);
        resolve(info)
      })
      .catch(function (error) {
        console.log('getOrderInfoError', error);
        reject(error)
      });
  })
}
// 提交订单
function submit() {
  return new Promise((resolve, reject) => {
    fly.post('https://www.fangyb.com:2039/biz/common/openSpeed.action', { userName: USERNAME, className: orderInfo.className, orderId: orderInfo.orderId }, { headers: { Authorization: authorization } })
      .then(function (res) {
        debug && console.log('--------submit--------');
        debug && console.log(res);
        resolve(res)
      })
      .catch(function (error) {
        console.log('submitError', error);
        reject(error)
      });
  })
}
// server酱通知
function notifyWechat(type, text) {
  fly.get(NOTIFY_TYPE[type], {
    title: type === 'success' ? '提速成功' : '提速失败',
    text: text
  })
    .then(function (res) {
      debug && console.log('------server酱通知------');
      debug && console.log(res);
    })
    .catch(function (error) {
      console.log('notifyWechatError', error);
    });
}
// 进程等待函数
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}